<script setup lang="ts">
import { ElMessage } from 'element-plus'
import { ref, onMounted } from 'vue'
import { reqHasTrademark, reqAddOrUpdateTrademark } from '@/apis/product/trademark'
import type { trademarkResponseData, Records, Trademark } from '@/apis/product/trademark/types'

const currentPage = ref<number>(1) // 分页器当前所在页数
const pageSize = ref<number>(3) // 每页条数
const total = ref<number>(0) // 全部品牌数量
const trademarkArr = ref<Records>([]) // 本页品牌数组
// 新增品牌列表收集的参数
const trademarkParams = ref<Trademark>({
    tmName: '',
    logoUrl: ''
})

// 控制dialog显示与隐藏
const dialogVisible = ref<boolean>(false)
// 服务器提供的品牌logo无法用了，因此随机生成一些替换
const logoUrls = ['https://picsum.photos/seed/brand1/100/50',
    'https://picsum.photos/seed/brand2/100/50',
    'https://picsum.photos/seed/brand3/100/50',
    'https://picsum.photos/seed/brand4/100/50',
    'https://picsum.photos/seed/brand5/100/50']

// 获取品牌列表
async function getTrademarkList(pager = 1) {
    currentPage.value = pager
    const res: trademarkResponseData = await reqHasTrademark(currentPage.value, pageSize.value)
    total.value = res.data.total
    trademarkArr.value = res.data.records.map((record: any) => ({
        ...record,
        logoUrl: logoUrls[Math.floor(Math.random() * logoUrls.length)]
    }))
}
onMounted(() => {
    getTrademarkList()
})

// 当每页条数改变时触发.
function handleSizeChange() {
    getTrademarkList()
}
// 添加品牌
function addTrademark() {
    dialogVisible.value = true
    // 每次点击新增按钮时清空之前的数据
    trademarkParams.value.id = 0
    trademarkParams.value.logoUrl = ''
    trademarkParams.value.tmName = ''
}
// 编辑品牌
function editTrademark(row: Trademark) {
    Object.assign(trademarkParams.value, row)
    dialogVisible.value = true
}
// dialog的取消按钮逻辑
function cancel() {
    dialogVisible.value = false
}
// dialog的确认按钮逻辑
async function confirm() {
    const result: any = await reqAddOrUpdateTrademark(trademarkParams.value)
     console.log('result', result)
    dialogVisible.value = false
    if(result.code === 200) {
        ElMessage({
            type: 'success',
            message: trademarkParams.value.id? '修改品牌成功' : '新增品牌成功'
        })
        // 重新请求最新的数据,并根据情况停留在相应的页面
        getTrademarkList(trademarkParams.value.id? currentPage.value : 1)
    }else {
        dialogVisible.value = false
        ElMessage({
            type: 'error',
            message: trademarkParams.value.id? '修改品牌失败' : '新增品牌失败'
        })
    }
   
    
}

// 上传图片前对图片进行约束
function beforeLogoUpload(rawFile: any) {
    if (rawFile.type === 'image/jpeg' || rawFile.type === 'image/png' || rawFile.type === 'image/gif') {
        if (rawFile.size / 1024 / 1024 > 4) {
            ElMessage({
                message: '图片大小不能超过4MB',
                type: 'error'
            })
            return false
        }
        return true
    } else {
        ElMessage({
            message: '请上传jpeg、png、gif格式的图片',
            type: 'error'
        })
        return false
    }
}
// 上传图片成功后的操作
function handleLogoSuccess(response: any) {
    trademarkParams.value.logoUrl = response.data
    
}

</script>

<template>
    <div>
        <!-- 品牌列表展示区域 -->
        <el-card>
            <!-- 添加品牌按钮 -->
            <el-button type="primary" icon="Plus" @click="addTrademark">添加品牌</el-button>
            <!-- 表格区域 -->
            <el-table :data="trademarkArr" border style="margin: 20px auto">
                <el-table-column label="序号" width="80px" align="center" type="index" />
                <el-table-column label="品牌名称" align="center" prop="tmName" />
                <el-table-column label="品牌LOGO" align="center">
                    <template #default="{ row }">
                        <img :src="row.logoUrl" alt="" style="width: 100px; height: 100px;">
                    </template>
                </el-table-column>
                <el-table-column label="品牌操作" align="center">
                    <template #default="{ row }">
                        <el-button type="primary" icon="Edit" @click="editTrademark(row)"></el-button>
                        <el-button type="danger" icon="Delete"></el-button>
                    </template>
                </el-table-column>
            </el-table>
            <!-- 分页器区域 -->
            <el-pagination @current-change="getTrademarkList" @size-change="handleSizeChange"
                v-model:current-page="currentPage" v-model:page-size="pageSize" :page-sizes="[3, 5, 7, 9]" background
                layout="prev, pager, next, jumper, -> ,total, sizes," :total="total" />
        </el-card>
        <!-- dialog区域，负责添加或编辑品牌 -->
        <el-dialog v-model="dialogVisible" :title="trademarkParams.id? '编辑品牌' : '添加品牌'">
            <el-form :model="trademarkParams" style="width: 80%;">
                <el-form-item label="品牌名称" label-width="80px">
                    <el-input v-model="trademarkParams.tmName" placeholder="请输入品牌名称"></el-input>
                </el-form-item>
                <el-form-item label="品牌LOGO" label-width="80px">
                    <el-upload class="avatar-uploader" action="/api/admin/product/fileUpload" :show-file-list="false"
                        :on-success="handleLogoSuccess" :before-upload="beforeLogoUpload">
                        <img v-if="trademarkParams.logoUrl" :src="trademarkParams.logoUrl" class="avatar" />
                        <el-icon v-else class="avatar-uploader-icon">
                            <Plus />
                        </el-icon>
                    </el-upload>
                </el-form-item>
            </el-form>
            <!-- 确认和删除按钮 -->
            <template #footer>
                <el-button type="info" @click="cancel">取消</el-button>
                <el-button type="primary" @click="confirm">确定</el-button>
            </template>
        </el-dialog>
    </div>
</template>

<style lang="scss" scoped>
.avatar-uploader .avatar {
    width: 178px;
    height: 178px;
    display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
    border: 1px dashed var(--el-border-color);
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
    border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    text-align: center;
}
</style>